/**
 * 
 */
package wpmp.portal.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import wpmp.security.client.SecurityConfig;
import wpmp.security.client.filter.SecurityFilter;

/**
 * @author Wayne.Wang<5waynewang@gmail.com>
 * @since 4:31:44 PM Apr 29, 2014
 */
public class PortalSecurityFilter extends SecurityFilter {

	public static final String PARAM_NAME_EXCLUSIONS = "exclusions";

	private final Set<String> excludesPattern = new HashSet<String>();
	private String contextPath;

	@Override
	protected boolean check(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
		// 例外情况
		if (isExclusion(req.getRequestURI())) {
			return true;
		}

		return super.check(req, resp);
	}

	public boolean isExclusion(String requestURI) {
		if (excludesPattern.isEmpty()) {
			return false;
		}

		if (contextPath != null && requestURI.startsWith(contextPath)) {
			requestURI = requestURI.substring(contextPath.length());
			if (!requestURI.startsWith("/")) {
				requestURI = "/" + requestURI;
			}
		}

		for (String pattern : excludesPattern) {
			if (StringUtils.equals(pattern, requestURI)) {
				return true;
			}
		}

		return false;
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		final String exclusions = config.getInitParameter(PARAM_NAME_EXCLUSIONS);
		if (exclusions != null && exclusions.trim().length() != 0) {
			excludesPattern.addAll(Arrays.asList(exclusions.split("\\s*,\\s*")));
		}
		contextPath = config.getServletContext().getContextPath();

		// 初始化客户端配置项
		new SecurityConfig().initByProperties();

		super.init(config);
	}
}
